package com.zhongyouyun.other.model;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongyouyun.admin.mapper.MenuMapper;
import com.zhongyouyun.admin.mapper.RoleMapper;
import com.zhongyouyun.admin.mapper.UserMapper;
import com.zhongyouyun.admin.model.*;
import com.zhongyouyun.admin.service.DeptService;
import com.zhongyouyun.admin.service.RoleService;
import com.zhongyouyun.admin.service.UserService;
import com.zhongyouyun.config.RedisConfig;
import com.zhongyouyun.cqyc.model.WxUserModel;
import com.zhongyouyun.cqyc.service.WxUserService;
import com.zhongyouyun.jyj.model.SspWxUserModel;
import com.zhongyouyun.jyj.service.SspWxUserService;
import com.zhongyouyun.utils.LongUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private UserService userService;

    @Autowired
    private SspWxUserService sspWxUserService;
    @Autowired
    private WxUserService wxUserService;


    @Resource
    private RedisConfig redisConfig;
    @Resource
    private DeptService deptService;
    @Resource
    private RoleService roleService;



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Object u = SecurityUtils.getSubject().getPrincipal();
        if (u instanceof UserModel) {
            UserModel userModel = (UserModel) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
            if (ObjectUtil.isNull(userModel)) {
                List<RoleModel> roleList = roleMapper.findByUserId(userModel.getId());
                Set<String> roles = new HashSet<String>();
                if (roleList.size() > 0) {
                    for (RoleModel role : roleList) {
                        roles.add(role.getName());
                        //List<Tmenu> menuList=menuRepository.findByRoleId(role.getId());
                        //根据角色id查询所有资源
                        List<MenuModel> menuList = menuMapper.selectMenusByRoleId(role.getId());
                        for (MenuModel menu : menuList) {
                            info.addStringPermission(menu.getName()); // 添加权限
                        }
                    }
                }
                info.setRoles(roles);
            }
        } else if (u instanceof UserModel) {

        } else if (u instanceof SspWxUserModel) {

        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String Id = (String) authenticationToken.getPrincipal();
        String[] s = Id.split("_");
        if ("user".equals(s[0])) {
            UserModel user = userService.getById(s[1]);
            if (user != null) {
                if (ObjectUtil.isNotEmpty(user.getDeptId())) {
                    //添加部门数据
                    QueryWrapper deptModelQueryWrapper = new QueryWrapper<DeptModel>();
                    deptModelQueryWrapper.eq("id", user.getDeptId());
                    List<DeptModel> deptModelList = deptService.selectList(deptModelQueryWrapper);
                    deptModelList.forEach(deptModel -> {
                        String chihids = deptService.getchild(deptModel.getId());
                        deptModel.setFullPathId(chihids);
                    });
                    user.setDeptModelList(deptModelList);
                }
                if (ObjectUtil.isNotEmpty(user.getRoleId())) {
                    //添加角色数据
                    user.setType("1");
                    List<RoleModel> roleModelList = roleService.selectbyList(LongUtil.Longva(user.getRoleId().split(",")));
                    boolean present = roleModelList.stream().filter(m -> "0".equals(m.getType())).findAny().isPresent();//是否有户主
                    if (present) {
                        user.setType("0");
                    }
                    user.setRoleModelList(roleModelList);
                }
                SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), user.getTrueName());
                simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getId().toString()));
             //   ShiroUtils.deleteCache(Id,"admin");
                return simpleAuthenticationInfo;
            } else {
                return null;
            }
        }else if("jyj".equals(s[0])){
            SspWxUserModel wxUserModel = sspWxUserService.getById(s[2]);
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(wxUserModel, "123456", "admin");
            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(wxUserModel.getId().toString()));
            return simpleAuthenticationInfo;
        }else if("cqyc".equals(s[0])){
            WxUserModel wxUserModel = wxUserService.getById(s[2]);
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(wxUserModel, "123456", "admin");
            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(wxUserModel.getId().toString()));
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
